package cn.tuling.standard;

import java.util.HashMap;
import java.util.Map;

/**
 * 常规实现方式
 */
public class FlyWeightTest {
    public static void main(String[] args) {
        FlyWeightFactory factory = new FlyWeightFactory();
        FlyWeight f01 = factory.getFlyWeight("a");
        FlyWeight f02 = factory.getFlyWeight("a");
        FlyWeight f03 = factory.getFlyWeight("a");


        FlyWeight f11 = factory.getFlyWeight("b");
        FlyWeight f12 = factory.getFlyWeight("b");


        f01.operate(new UnsharedConcreteFlyWeight("第一次调用a"));
        f02.operate(new UnsharedConcreteFlyWeight("第二次调用a"));
        f03.operate(new UnsharedConcreteFlyWeight("第三次调用a"));


        f11.operate(new UnsharedConcreteFlyWeight("第一次调用b"));
        f12.operate(new UnsharedConcreteFlyWeight("第二次调用b"));
    }
}

class FlyWeightFactory {
    private Map<String, FlyWeight> flyWeightMap = new HashMap<>(1 << 4);

    public FlyWeight getFlyWeight(String key) {
        FlyWeight flyWeight = flyWeightMap.get(key);
        if (flyWeight == null) {
            flyWeight = new ConcreteFlyWeight1(key);
            flyWeightMap.put(key, flyWeight);
        } else {
            System.out.println("享元对象" + key + "已被创建");
        }

        return flyWeight;
    }
}

class UnsharedConcreteFlyWeight {
    private String info;

    public UnsharedConcreteFlyWeight(String info) {
        this.info = info;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}

interface FlyWeight {
    void operate(UnsharedConcreteFlyWeight unsharedConcreteFlyWeight);
}

class ConcreteFlyWeight1 implements FlyWeight {
    private String key;

    public ConcreteFlyWeight1(String key) {
        System.out.println("享元对象" + key + "被创建");
        this.key = key;
    }


    @Override
    public void operate(UnsharedConcreteFlyWeight unsharedConcreteFlyWeight) {
        System.out.println("具体享元对象" + key + "被执行");
        System.out.println("非享元信息：" + unsharedConcreteFlyWeight.getInfo());
    }
}
